import cherrypy
from django.utils import simplejson

from google.appengine.ext.db import Error

from app.controllers.post import PostController
from app.controllers.department import DepartmentController
from app.dutil import toClass

class PostHandler(object):
	@cherrypy.expose
	def index(self):
		pass
		
	@cherrypy.expose	
	def posts(self, *args, **kwargs):
		rsPosts = PostController.getPosts()
		dPosts = dict([('page',1), ('rows',[rPost.toCells() for rPost in rsPosts])])
		dPosts.update(total=len(dPosts['rows']))
		return simplejson.dumps(dPosts)
	
	@cherrypy.expose
	def vpost(self,id=None):
		try:
			rsDepts = DepartmentController.getDepartments()
			if id is not None:
				rsPost = PostController.getPost(int(id))
				dPost = rsPost.toRow()
				dPost.update([('depts',[rDept.toRows(['name']) for rDept in rsDepts])])
				return simplejson.dumps(dPost)
			else:
				return simplejson.dumps([rDept.toRows(['name']) for rDept in rsDepts])
		except TypeError:
			return None
			
	@cherrypy.expose
	def upost(self, *args, **kwargs):
		if kwargs:
			brs = PostController.updatePost(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def apost(self, *args, **kwargs):
		if kwargs:
			brs = PostController.addPost(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def dpost(self, id=None):
		if id is not None:
			brs = PostController.deletePost(id)
		else: brs = False
		
		return simplejson.dumps(dict([('success',brs)]))